﻿using System;
using System.Data;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Models;
using System.Drawing;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using ChinaDynastyTours.Assets;
using ChinaDynastyTours.Assets.DataSet;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace ChinaDynastyTours.Views
{
    public partial class BatchTrainFlightOrderForm : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _dtFlightOrderData;
        private DataTable _dtTrainOrderData;

        private UiState _uiState = new UiState();

        private void EnableOrDisable(BindingSource bindSource, bool state)
        {
            //UiState uiState = new UiState();
            bindSource.DataSource = _uiState;

            _uiState.IsEnabled = state;
            bindSource.ResetCurrentItem();
        }


        public BatchTrainFlightOrderForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 为飞机、火车提供统一的行程计划显示函数
        /// </summary>
        /// <param name="gv"></param>
        private void DisplayScheduleData(GridView gv)
        {
            if(gv.FocusedRowHandle<0) return;

            string tourGroupId = gv.GetRowCellValue(gv.FocusedRowHandle, "TourgroupID").ToString();
            string tourGroupScheduleId = gv.GetRowCellValue(gv.FocusedRowHandle, "TourGroupScheduleID").ToString();
            DataTable tmpDt = TeamGroupCtrl.GetTourGroupSchedule(tourGroupId).Tables[0];
            scheduleGridControl.DataSource = tmpDt;

            //定位当前选中的Order对应的行程计划ID
            for(int i=0;i<tmpDt.Rows.Count;i++)
            {
                if (tmpDt.Rows[i]["TourGroupScheduleID"].ToString() == tourGroupScheduleId)
                {
                    ScheduleGridView.FocusedRowHandle = i;
                    break;
                }
            }
        }
        /// <summary>
        /// 选择所有行
        /// </summary>
        /// <param name="isSelectedAll"></param>
        /// <param name="dataSource"></param>
        private void SelectAllRowData(bool isSelectedAll, DataTable dataSource)
        {
            foreach (DataRow dr in dataSource.Rows)
                dr["Selected"] = isSelectedAll;
        }

        private void TrainFlightForm_Load(object sender, EventArgs e)
        {
            //火车默认为本月1日起，一年后1日止
            trainDateStart.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year, DateTime.Now.Month));
            trainDateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + 1, DateTime.Now.Month));

            //飞机默认为本月1日起，一年后月1日止
            flightDateStart.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year, DateTime.Now.Month));
            flightDateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + 1, DateTime.Now.Month));

            //半年后1日止
            //flightDateEnd.EditValue = DateTime.Parse(string.Format("{0}-{1}-01", DateTime.Now.Year + DateTime.Now.Month / 7, (DateTime.Now.Month + 5) % 12 + 1));


            //初始化团下拉列表
            DataSet ds = TeamGroupCtrl.GetAllIDForTeamGroup();
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    btnTrainTeamGroupID.Properties.Items.Add(dr["TourGroupID"].ToString().Trim());
                    btnFlightTeamGroupID.Properties.Items.Add(dr["TourGroupID"].ToString().Trim());
                }
            }
            //初始化‘席位’信息
            tbTrainSeat.Properties.Items.AddRange(Enum.GetNames(typeof(TrainSeatEnum)));
            tbFlightSeat.Properties.Items.AddRange(Enum.GetNames(typeof(FlightSeatEnum)));

            btnTrainRefresh.PerformClick();

        }
        /// <summary>
        /// 供应商条件查询按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProviders_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
            {
                DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                btnEdit.Tag = null;
                btnEdit.EditValue = null;
            }
            else
            {
                ProviderSelectedToolForm providerForm = new ProviderSelectedToolForm();
                if (sender.Equals(tbTrainProviders) || sender.Equals(btnTrainProviders))
                    providerForm._ProviderTypes = new ProviderTypeEnum[] { ProviderTypeEnum.火车票 };
                if (sender.Equals(tbFlightProviders) || sender.Equals(btnFlightProviders))
                    providerForm._ProviderTypes = new ProviderTypeEnum[] { ProviderTypeEnum.飞机票 };

                if (providerForm.ShowDialog(this) == DialogResult.OK)
                {
                    DevExpress.XtraEditors.ButtonEdit btnEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                    btnEdit.Tag = providerForm.ReturnProviderID;
                    btnEdit.EditValue = providerForm.ReturnProviderName;
                }
            }
        }


        #region 火车信息处理

        private void btnTrainRefresh_Click(object sender, EventArgs e)
        {
            string providerId = btnTrainProviders.Tag == null ? "" : btnTrainProviders.Tag.ToString();

            OrderStateEnum orderState = EnumHelper.OrderState_Str2Enum(btnTrainOrderState.Text, true);
            _dtTrainOrderData = TrainOrderCtrl.GetTrainOrderData(btnTrainTeamGroupID.Text, providerId, trainDateStart.DateTime, trainDateEnd.DateTime, orderState);

            //设定‘打印’、‘预览’、‘EMail’、‘提交审核’与修改内容面板的可用状态
            if (_dtTrainOrderData != null)
                EnableOrDisable(uiStateBindingSource, _dtTrainOrderData.Rows.Count > 0);

            trainGridControl.DataSource = AddGridSelectedColumn(_dtTrainOrderData);
            tbTrainAll.Checked = false; 
            InitializeGUIData();

            //SelectAllRowData(false, _dtTrainOrderData);

            ////刷新时显示行程计划信息
            //scheduleGridControl.DataSource = TeamGroupCtrl.GetTourGroupSchedule(btnTrainTeamGroupID.Text).Tables[0];

            //焦点定位最后一条，增加一条后刷新定位最后一条（普通刷新也定位最后一条）
            //if (trainGridView.RowCount > 0)
            //    trainGridView.FocusedRowHandle = 1;
        }
        private void trainGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;

            GridView gv = sender as GridView;
            string tourGroupId = gv.GetRowCellValue(e.FocusedRowHandle, "TourgroupID").ToString();
            //审核状态后的不能新增和删除内容
            TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(tourGroupId);
            if (state == TeamStateEnum.成行||state == TeamStateEnum.分配)
            {
                //btnAddTrainOrder.Enabled = true;
                btnDeleteTrainOrder.Enabled = true;
                TrainDataModifyPanel.Enabled = true;
            }
            else
            {
                //btnAddTrainOrder.Enabled = false;
                btnDeleteTrainOrder.Enabled = false;
                TrainDataModifyPanel.Enabled = false;
            }

            DisplayScheduleData(gv);
        }

        #region 初始化绑定处理
        private void InitializeGUIData()
        {
            if (_dtTrainOrderData != null && _dtTrainOrderData.Rows.Count > 0)
            {
                //清除已有绑定
                tbTrainSeat.DataBindings.Clear();

                tbTrainCode.DataBindings.Clear();
                tbTrainBeginPosition.DataBindings.Clear();
                tbTrainBeginPositionDate.DataBindings.Clear();
                tbTrainBeginPositionTime.DataBindings.Clear();
                tbTrainEndPosition.DataBindings.Clear();
                tbTrainEndPositionDate.DataBindings.Clear();
                tbTrainEndPositionTime.DataBindings.Clear();

                tbAdultNum.DataBindings.Clear(); 
                tbChildNum.DataBindings.Clear();
                tbAccompanyNum.DataBindings.Clear();

                tbHardSleeperTopQuantity.DataBindings.Clear();
                tbHardSleeperMiddleQuantity.DataBindings.Clear();
                tbHardSleeperBottomQuantity.DataBindings.Clear();
                tbHardSleeperTopPrice.DataBindings.Clear();
                tbHardSleeperMiddlePrice.DataBindings.Clear();
                tbHardSleeperBottomPrice.DataBindings.Clear();

                tbSoftSleeperTopQuantity.DataBindings.Clear();
                tbSoftSleeperBottomQuantity.DataBindings.Clear();
                tbHighBoxQuantity.DataBindings.Clear();
                tbSoftSleeperTopPrice.DataBindings.Clear();
                tbSoftSleeperBottomPrice.DataBindings.Clear();
                tbHighBoxPrice.DataBindings.Clear();

                tbHardSeatQuantity.DataBindings.Clear();
                tbSoftSeatQuantity.DataBindings.Clear();
                tbChildSeatQuantity.DataBindings.Clear();
                tbHardSeatPrice.DataBindings.Clear();
                tbSoftSeatPrice.DataBindings.Clear();
                tbChildSeatPrice.DataBindings.Clear();

                tbTrainProviders.DataBindings.Clear();
                tbTrainRemark.DataBindings.Clear();
                tbTrainHandlingCharge.DataBindings.Clear();
                tbTrainTotalPrice.DataBindings.Clear();

                //与UI绑定
                tbTrainSeat.DataBindings.Add("EditValue", _dtTrainOrderData, "Seat");

                tbTrainCode.DataBindings.Add("EditValue", _dtTrainOrderData, "TrainCode");
                tbTrainBeginPosition.DataBindings.Add("EditValue", _dtTrainOrderData, "BeginPosition");
                tbTrainBeginPositionDate.DataBindings.Add("EditValue", _dtTrainOrderData, "StartDate");
                tbTrainBeginPositionTime.DataBindings.Add("EditValue", _dtTrainOrderData, "StartTime");
                tbTrainEndPosition.DataBindings.Add("EditValue", _dtTrainOrderData, "EndPosition");
                tbTrainEndPositionDate.DataBindings.Add("EditValue", _dtTrainOrderData, "EndDate");
                tbTrainEndPositionTime.DataBindings.Add("EditValue", _dtTrainOrderData, "EndTime");

                tbAdultNum.DataBindings.Add("EditValue", _dtTrainOrderData, "AdultNum");
                tbChildNum.DataBindings.Add("EditValue", _dtTrainOrderData, "ChildNum");
                tbAccompanyNum.DataBindings.Add("EditValue", _dtTrainOrderData, "AccompanyNum");

                tbHardSleeperTopQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperTopQuantity");
                tbHardSleeperMiddleQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperMiddleQuantity");
                tbHardSleeperBottomQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperBottomQuantity");
                tbHardSleeperTopPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperTopPrice");
                tbHardSleeperMiddlePrice.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperMiddlePrice");
                tbHardSleeperBottomPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSleeperBottomPrice");

                tbSoftSleeperTopQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSleeperTopQuantity");
                tbSoftSleeperBottomQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSleeperBottomQuantity");
                tbHighBoxQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "HighBoxQuantity");
                tbSoftSleeperTopPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSleeperTopPrice");
                tbSoftSleeperBottomPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSleeperBottomPrice");
                tbHighBoxPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "HighBoxPrice");

                tbHardSeatQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSeatQuantity");
                tbSoftSeatQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSeatQuantity");
                tbChildSeatQuantity.DataBindings.Add("EditValue", _dtTrainOrderData, "ChildSeatQuantity");
                tbHardSeatPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "HardSeatPrice");
                tbSoftSeatPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "SoftSeatPrice");
                tbChildSeatPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "ChildSeatPrice");

                tbTrainProviders.DataBindings.Add("EditValue", _dtTrainOrderData, "ProviderName");
                tbTrainProviders.DataBindings.Add("Tag", _dtTrainOrderData, "ProviderID");
                tbTrainRemark.DataBindings.Add("EditValue", _dtTrainOrderData, "Remark");
                tbTrainHandlingCharge.DataBindings.Add("EditValue", _dtTrainOrderData, "HandlingCharge");
                tbTrainTotalPrice.DataBindings.Add("EditValue", _dtTrainOrderData, "Budget");
            }
        } 
        #endregion

        #region 火车预订信息修改
        private void btnTrainCalculationPrice_Click(object sender, EventArgs e)
        {
            decimal totalPrice = int.Parse(tbHardSleeperTopQuantity.Text) * decimal.Parse(tbHardSleeperTopPrice.EditValue.ToString()) +
                                int.Parse(tbHardSleeperMiddleQuantity.Text) * decimal.Parse(tbHardSleeperMiddlePrice.EditValue.ToString()) +
                                int.Parse(tbHardSleeperBottomQuantity.Text) * decimal.Parse(tbHardSleeperBottomPrice.EditValue.ToString()) +
                                int.Parse(tbSoftSleeperTopQuantity.Text) * decimal.Parse(tbSoftSleeperTopPrice.EditValue.ToString()) +
                                int.Parse(tbSoftSleeperBottomQuantity.Text) * decimal.Parse(tbSoftSleeperBottomPrice.EditValue.ToString()) +
                                int.Parse(tbHighBoxQuantity.Text) * decimal.Parse(tbHighBoxPrice.EditValue.ToString()) +
                                int.Parse(tbHardSeatQuantity.Text) * decimal.Parse(tbHardSeatPrice.EditValue.ToString()) +
                                int.Parse(tbSoftSeatQuantity.Text) * decimal.Parse(tbSoftSeatPrice.EditValue.ToString()) +
                                int.Parse(tbChildSeatQuantity.Text) * decimal.Parse(tbChildSeatPrice.EditValue.ToString()) +
                                decimal.Parse(tbTrainHandlingCharge.EditValue.ToString());
            tbTrainTotalPrice.EditValue = totalPrice;
        }

        private void btnTrainSave_Click(object sender, EventArgs e)
        {
            if (_dtTrainOrderData == null || _dtTrainOrderData.Rows.Count == 0) return;

            DataRowView drv = (BindingContext[_dtTrainOrderData].Current as DataRowView);

            TrainOrderEntity trainOrderEntity = new TrainOrderEntity()
            {
                //变化内容提交
                HardSleeperTopQuantity = int.Parse(tbHardSleeperTopQuantity.Text),
                HardSleeperTopPrice = decimal.Parse(tbHardSleeperTopPrice.EditValue.ToString()),
                HardSleeperMiddleQuantity = int.Parse(tbHardSleeperMiddleQuantity.Text),
                HardSleeperMiddlePrice = decimal.Parse(tbHardSleeperMiddlePrice.EditValue.ToString()),
                HardSleeperBottomQuantity = int.Parse(tbHardSleeperBottomQuantity.Text),
                HardSleeperBottomPrice = decimal.Parse(tbHardSleeperBottomPrice.EditValue.ToString()),
                SoftSleeperTopQuantity = int.Parse(tbSoftSleeperTopQuantity.Text),
                SoftSleeperTopPrice = decimal.Parse(tbSoftSleeperTopPrice.EditValue.ToString()),
                SoftSleeperBottomQuantity = int.Parse(tbSoftSleeperBottomQuantity.Text),
                SoftSleeperBottomPrice = decimal.Parse(tbSoftSleeperBottomPrice.EditValue.ToString()),
                HighBoxQuantity = int.Parse(tbHighBoxQuantity.Text),
                HighBoxPrice = decimal.Parse(tbHighBoxPrice.EditValue.ToString()),
                HardSeatQuantity = int.Parse(tbHardSeatQuantity.Text),
                HardSeatPrice = decimal.Parse(tbHardSeatPrice.EditValue.ToString()),
                SoftSeatQuantity = int.Parse(tbSoftSeatQuantity.Text),
                SoftSeatPrice = decimal.Parse(tbSoftSeatPrice.EditValue.ToString()),
                ChildSeatQuantity = int.Parse(tbChildSeatQuantity.Text),
                ChildSeatPrice = decimal.Parse(tbChildSeatPrice.EditValue.ToString()),
                HandlingCharge = decimal.Parse(tbTrainHandlingCharge.EditValue.ToString()),
                TrainCode = tbTrainCode.Text,
                StartDate = tbTrainBeginPositionDate.DateTime.ToString("yyyy-MM-dd"),
                EndDate = tbTrainEndPositionDate.DateTime.ToString("yyyy-MM-dd"),
                StartTime = DateTime.Parse(tbTrainBeginPositionTime.Text).ToString("HH:mm:ss"),
                EndTime = DateTime.Parse(tbTrainEndPositionTime.Text).ToString("HH:mm:ss"),
                BeginPosition = tbTrainBeginPosition.Text,
                EndPosition = tbTrainEndPosition.Text,
                Remark = tbTrainRemark.Text,
                 
                AdultNum= int.Parse(tbAdultNum.EditValue.ToString()),
                AccompanyNum = int.Parse(tbAccompanyNum.EditValue.ToString()),
                ChildNum= int.Parse(tbChildNum.EditValue.ToString()),

                ProviderID = tbTrainProviders.Tag == null ? -1 : int.Parse(tbTrainProviders.Tag.ToString()),
                ProviderName = tbTrainProviders.Text,

                Seat = tbTrainSeat.Text,

                TrainOrderID = int.Parse(drv["TrainOrderID"].ToString())  /*更新条件字段*/

            };
            //获取id并更新数据
            //string trainOrderId = (BindingContext[_dtTrainOrderData].Current as DataRowView).Row["TrainOrderID"].ToString();
            //TrainOrderCtrl.UpdateTrainOrderData(trainOrderId, trainOrderEntity);

            ExpenseEntity expense = new ExpenseEntity()
            {
                ExpenseID = int.Parse(drv["ExpenseID"].ToString()), /*重点字段*/
                //没变化的值就不更新了
                //TourgroupID = drv["TourgroupID"].ToString(),
                //TourgroupName = drv["TourgroupName"].ToString(),
                ProviderID = tbTrainProviders.Tag == null ? -1 : int.Parse(tbTrainProviders.Tag.ToString()),
                ProviderName = tbTrainProviders.Text,
                Budget = decimal.Parse(tbTrainTotalPrice.EditValue.ToString()),
                ServiceName = tbTrainBeginPosition.Text + "-" + tbTrainEndPosition.Text+" 火车票"
                //Status = drv["Status"].ToString(),
                //Remark = drv["Remark"].ToString(),
                //TypeBelong = ProviderTypeEnum.火车票.ToString(),
            };
            TrainOrderCtrl.UpdateTrainOrderData(expense, trainOrderEntity);

            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(drv["TourgroupID"].ToString());

            MessageBox.Show("保存成功！", "保存数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //刷新界面，因希望保存后，列表焦点行不变，于是不刷新界面。缺点是不能实时刷新，要换一行才发现变化。
            //btnRefresh.PerformClick();
        }
        /// <summary>
        /// 选择火车车次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTrainCode_Click(object sender, EventArgs e)
        {
            TrainOrderForm trainOrderForm = new TrainOrderForm()
            {
                _StartCity = tbTrainBeginPosition.EditValue.ToString(),
                _EndCity = tbTrainEndPosition.EditValue.ToString(),
            };
            if (trainOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值
            {
                tbTrainCode.EditValue = trainOrderForm._TrainCode;
                tbTrainBeginPosition.EditValue = trainOrderForm._StartCity;
                tbTrainEndPosition.EditValue = trainOrderForm._EndCity;
                tbTrainBeginPositionTime.EditValue = trainOrderForm._StartTime;
                tbTrainEndPositionTime.EditValue = trainOrderForm._EndTime;
            }
        } 
        #endregion

        #region 打印、预览、提交审核事件处理
        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTrainExpenseSubmit_Click(object sender, EventArgs e)
        {
            if (_dtTrainOrderData == null || _dtTrainOrderData.Rows.Count <= 0) return;

            if (MessageBox.Show("您确认提交选中内容进行审核吗？", "打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //trainGridView.ClearSelection();
                int[] rowIds = MutilRow(trainGridView);
                string expenseId = "", status = "";

                foreach (int id in rowIds)
                {
                    //tourgroupId = trainGridView.GetRowCellValue(id, "TourgroupID").ToString();
                    ////审核状态后的不能新增和删除内容
                    //TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(tourgroupId);
                    //if (state == TeamStateEnum.审核 || state == TeamStateEnum.终结)
                    //{
                    //    msg.Clear();
                    //    msg.AppendText(string.Format("计划号：{0}的团状态为‘{1}’，不能提交审核", tourgroupId, state));
                    //    messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                    //    return;
                    //}
                    status = trainGridView.GetRowCellValue(id, "Status").ToString();
                    if (status == ExpenseStatusEnum.计划.ToString())
                    {
                        expenseId = trainGridView.GetRowCellValue(id, "ExpenseID").ToString();
                        ExpensesCtrl.UpdateExpenseStatusData(expenseId, ExpenseStatusEnum.待审核);

                        trainGridView.SetRowCellValue(id, "Status", ExpenseStatusEnum.待审核);
                    }
                }
                MessageBox.Show("提交完毕！", "提交审核", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreview_Click(object sender, EventArgs e)
        {
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(trainGridView, out rowIds))
                return;

            //获取供应商名称列表及选择的数据行数据
            string providerNames = "";
            BatchTrainDataSet ds = new BatchTrainDataSet();

            for (int i = 0; i < rowIds.Length; i++)
            {
                //ds.Tables["Train"].ImportRow(trainGridView.GetDataRow(rowIds[i]));

                if (trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                {
                    DataRow tmpDr = trainGridView.GetDataRow(rowIds[i]);

                    ds.Tables["Train"].ImportRow(tmpDr);
                    ds.Tables["Train"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                    ds.Tables["Train"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                    ds.Tables["Train"].Rows[i]["AdultNum"] = int.Parse(tmpDr["AdultNum"].ToString()) + int.Parse(tmpDr["ChildNum"].ToString());
                }

                if (trainGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(trainGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                    providerNames = string.Format("{0}　{1}", providerNames, trainGridView.GetRowCellValue(rowIds[i], "ProviderName"));
            }
            BatchTrainOrderReport rpt = new BatchTrainOrderReport(providerNames);
            rpt.DataSource = ds;
            //new PrintPreviewForm(rpt, "").ShowDialog();
            rpt.ShowPreviewDialog();
        }
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(trainGridView, out rowIds))
                return;

            if (MessageBox.Show("您确认打印选中的火车预订信息吗？", "打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //获取供应商名称列表及选择的数据行数据
                string providerNames = "";
                BatchTrainDataSet ds = new BatchTrainDataSet();

                for (int i = 0; i < rowIds.Length; i++)
                {
                    if ( trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                    {
                        DataRow tmpDr = trainGridView.GetDataRow(rowIds[i]);

                        ds.Tables["Train"].ImportRow(tmpDr);
                        ds.Tables["Train"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                        ds.Tables["Train"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                        ds.Tables["Train"].Rows[i]["AdultNum"] = int.Parse(tmpDr["AdultNum"].ToString()) + int.Parse(tmpDr["ChildNum"].ToString());
                    }

                    if (trainGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(trainGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                        providerNames = string.Format("{0}　{1}", providerNames, trainGridView.GetRowCellValue(rowIds[i], "ProviderName"));
                }
                BatchTrainOrderReport rpt = new BatchTrainOrderReport(providerNames);
                rpt.DataSource = ds;
                if (rpt.PrintDialog() == DialogResult.OK)//打印完毕之后将订单状态变为‘已定’
                {
                    string trainOrderId = "";
                    foreach (int id in rowIds)
                    {
                        if (trainGridView.GetRowCellValue(id, "Status").ToString() != OrderStateEnum.取消.ToString())
                        {
                            trainOrderId = trainGridView.GetRowCellValue(id, "TrainOrderID").ToString();
                            TrainOrderCtrl.UpdateTrainOrderStateData(trainOrderId, OrderStateEnum.已订);
                            trainGridView.SetRowCellValue(id, "OrderState", OrderStateEnum.已订);
                        }
                    }
                    MessageBox.Show("打印完毕！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// 发送EMail
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEmail_Click(object sender, EventArgs e)
        {
            if (_dtTrainOrderData == null || _dtTrainOrderData.Rows.Count <= 0) return;

            #region 生成报表
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(trainGridView, out rowIds))
                return;

            //获取供应商名称列表及选择的数据行数据
            string providerNames = "";
            BatchTrainDataSet ds = new BatchTrainDataSet();

            for (int i = 0; i < rowIds.Length; i++)
            {
                if (trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                {
                    DataRow tmpDr = trainGridView.GetDataRow(rowIds[i]);

                    ds.Tables["Train"].ImportRow(tmpDr);
                    ds.Tables["Train"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                    ds.Tables["Train"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                    ds.Tables["Train"].Rows[i]["AdultNum"] = int.Parse(tmpDr["AdultNum"].ToString()) + int.Parse(tmpDr["ChildNum"].ToString());
                }

                if (trainGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(trainGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && trainGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                    providerNames = string.Format("{0}　{1}", providerNames, trainGridView.GetRowCellValue(rowIds[i], "ProviderName"));
            }
            BatchTrainOrderReport rpt = new BatchTrainOrderReport(providerNames);
            rpt.DataSource = ds;

            #endregion

            #region 发送EMail

            //ProviderEntity entity;
            //StringBuilder info = new StringBuilder();
            List<string> receiveMail = new List<string>();
            //StringBuilder recipients = new StringBuilder();

            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "火车预订单.pdf");
            rpt.ExportToPdf(file);
            if (File.Exists(file))
            {
                string ReplyAddress = SysParameterCtrl.GetValueForKey("TicketMailAddress");
                //string ServerMailAddress = SysParameterCtrl.GetValueForKey("TicketMailServer");
                //string ServerMailPassword = SysParameterCtrl.GetValueForKey("TicketMailPassword");
                //string ServerMailSmtp = SysParameterCtrl.GetValueForKey("TicketMailSmtp");
                List<string> files = new List<string>();
                files.Add(file);

                string providerID = trainGridView.GetRowCellValue(rowIds[0], "ProviderID").ToString();
                if (string.IsNullOrEmpty(providerID) || providerID=="-1")
                {
                    MessageBox.Show("尚未确定供应商", "信息提示");
                    return;
                }
                ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);
                string emailAddress = provider.email.ToString();
                string recipients = trainGridView.GetRowCellValue(rowIds[0], "ProviderName").ToString();

                if (string.IsNullOrEmpty(emailAddress) || (emailAddress.IndexOf("@") < 1) || (emailAddress.Substring(emailAddress.IndexOf("@")).IndexOf(".") < 2))
                {
                    MessageBox.Show("当前接收人地址格式不正确", "信息提示");
                    return;
                }

                for (int i = 1; i < rowIds.Length; i++)
                {
                    if (providerID != trainGridView.GetRowCellValue(rowIds[i], "ProviderID").ToString())
                    {
                        MessageBox.Show("请选择同一收件人", "信息提示");
                        return;
                    }
                }
                receiveMail.Add(emailAddress);

                if (EMailHelper.SendMail(receiveMail, "火车预订", "请收到此通知后回复确认。\r\n\r\n北京龙润国际旅行社有限公司", files, ReplyAddress, recipients, "", "", LogTypeEnum.计调类))
                {
                    MessageBox.Show("邮件发送成功！", "信息提示");
                    string TrainOrderID = "";
                    foreach (int id in rowIds)
                    {
                        if (trainGridView.GetRowCellValue(id, "Status").ToString() != OrderStateEnum.取消.ToString())
                        {
                            TrainOrderID = trainGridView.GetRowCellValue(id, "TrainOrderID").ToString();
                            TrainOrderCtrl.UpdateTrainOrderStateData(TrainOrderID, OrderStateEnum.已订);
                            trainGridView.SetRowCellValue(id, "OrderState", OrderStateEnum.已订);
                        }
                    }

                }
                else
                    MessageBox.Show("邮件发送失败，详情请查看日志", "信息提示");
                File.Delete(file);
            }
            else
            {
                MessageBox.Show("发送失败,生成报表文件失败！", "信息提示");
            }
            #endregion
        } 

        #endregion

        #region 火车预订的新增、删处理（在“火车飞机”计调处可新增项的新需求）

        private void btnAddTrainOrder_Click(object sender, EventArgs e)
        {
            if (btnTrainTeamGroupID.Text == "")
            {
                MessageBox.Show("您还没有选择‘计划号’！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ////先刷新行程，使之与当前选择团号一致
            //DisplayScheduleData(trainGridView);

            ////判断当前是否有选择的团一致行程计划
            //if (ScheduleGridView.FocusedRowHandle < 0)
            //{
            //    MessageBox.Show(string.Format("团‘{0}’没有安排行程计划，无法添加预订！", btnTrainTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}
            string tourGroupName = TeamGroupCtrl.GetTeamGroupNameById(btnTrainTeamGroupID.Text);

            TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(btnTrainTeamGroupID.Text);
            if (state != TeamStateEnum.成行 && state != TeamStateEnum.分配)
            {
                MessageBox.Show(string.Format("团‘{0}’未成行或已审核，无法添加预订！", btnTrainTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int scheduleId = TeamGroupCtrl.GetFirstTourgroupScheduleID(btnTrainTeamGroupID.Text);

            //判断当前是否有选择的团一致行程计划
            if (scheduleId < 0)
            {
                MessageBox.Show(string.Format("团‘{0}’没有安排行程计划，无法添加预订！", btnTrainTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //创建火车预定信息内容
            TrainOrderEntity trainOrder = new TrainOrderEntity();
            trainOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            trainOrder.TrainCode = ""; trainOrder.BeginPosition = ""; trainOrder.EndPosition = ""; trainOrder.StartTime = "00:00:00";
            trainOrder.EndTime = "00:00:00"; trainOrder.StartDate = DateTime.Now.ToString("yyyy-MM-dd"); trainOrder.EndDate = DateTime.Now.ToString("yyyy-MM-dd");
            trainOrder.HardSeatQuantity = 0; trainOrder.SoftSeatQuantity = 0; trainOrder.HardSleeperBottomQuantity = 0; trainOrder.HardSleeperMiddleQuantity = 0;
            trainOrder.HardSleeperTopQuantity = 0; trainOrder.HighBoxQuantity = 0; trainOrder.ChildSeatQuantity = 0; trainOrder.Remark = "";

            trainOrder.SoftSleeperBottomPrice = 0; trainOrder.SoftSleeperBottomQuantity = 0;
            trainOrder.SoftSleeperTopPrice = 0; trainOrder.SoftSleeperTopQuantity = 0;
            trainOrder.HandlingCharge = 0; trainOrder.HardSeatPrice = 0;
            trainOrder.ChildSeatPrice = 0; trainOrder.HardSleeperTopPrice = 0;
            trainOrder.HardSleeperMiddlePrice = 0; trainOrder.SoftSeatPrice = 0;
            trainOrder.HardSleeperBottomPrice = 0; trainOrder.HighBoxPrice = 0;

            trainOrder.AccompanyNum = 0; trainOrder.AdultNum = 0;
            trainOrder.ChildNum = 0; trainOrder.TourgroupID = btnTrainTeamGroupID.Text;
            trainOrder.TourgroupName = tourGroupName; trainOrder.TourGroupScheduleID = scheduleId;
            trainOrder.ProviderID = -1; trainOrder.ProviderName = "";

            trainOrder.Seat = "";

            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = btnTrainTeamGroupID.Text,
                TourgroupName = tourGroupName,
                ProviderID = -1,
                ProviderName = "",
                ServiceName = "",
                Budget = 0,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.火车票.ToString(),
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name,
                TourGroupScheduleID = scheduleId,
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 4,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(4)//同上
            };
            //trainGridView
            //e.RowHandle
            TrainOrderCtrl.CreateTrainOrderAndExpenseData(expense, trainOrder);
            //刷新数据
            btnTrainRefresh.PerformClick();
        }

        private void btnDeleteTrainOrder_Click(object sender, EventArgs e)
        {
            if (trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString()
                || trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "OrderState").ToString() != OrderStateEnum.未订.ToString())
            {
                MessageBox.Show("该预订已生效，不能删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            //删除已有火车预订信息
            if (MessageBox.Show("确定删除选中的预订信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int trainOrderID = int.Parse(trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "TrainOrderID").ToString());
                TrainOrderCtrl.DeleteTrainOrder(trainOrderID);
                //刷新
                trainGridView.DeleteRow(trainGridView.FocusedRowHandle);
            }
        }

        private void btnCancelTrainOrder_Click(object sender, EventArgs e)
        {
            if (trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString())
            {
                MessageBox.Show("该预订已支付或提交审核，不能取消！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (MessageBox.Show("确定取消选中的预订信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string expenseId = trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "ExpenseID").ToString();
                string trainOrderId = trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "TrainOrderID").ToString();
                ExpensesCtrl.UpdateExpenseStatusData(expenseId, ExpenseStatusEnum.取消);
                TrainOrderCtrl.UpdateTrainOrderStateData(trainOrderId, OrderStateEnum.取消);

                //刷新
                trainGridView.SetRowCellValue(trainGridView.FocusedRowHandle, "Status", ExpenseStatusEnum.取消);
                trainGridView.SetRowCellValue(trainGridView.FocusedRowHandle, "OrderState", ExpenseStatusEnum.取消);
            }

        }

        #endregion        

        #endregion

        #region 飞机信息处理

        private void btnFlightRefresh_Click(object sender, EventArgs e)
        {
            string providerId = btnFlightProviders.Tag == null ? "" : btnFlightProviders.Tag.ToString();
            
            OrderStateEnum orderState = EnumHelper.OrderState_Str2Enum(btnFlightOrderState.Text, true);
            _dtFlightOrderData = FlightOrderCtrl.GetFlightOrderData(btnFlightTeamGroupID.Text, providerId, flightDateStart.DateTime, flightDateEnd.DateTime, orderState);

            //设定‘打印’、‘预览’、‘EMail’、‘提交审核’与修改内容面板的可用状态
            if (_dtFlightOrderData != null)
                EnableOrDisable(uiStateBindingSource1, _dtFlightOrderData.Rows.Count > 0);

            flightGridControl.DataSource = AddGridSelectedColumn(_dtFlightOrderData);
            tbFlightAll.Checked = false;
            InitializeFlightGUIData();


            //SelectAllRowData(false, _dtFlightOrderData);

            //刷新时显示行程计划信息
            //scheduleGridControl.DataSource = TeamGroupCtrl.GetTourGroupSchedule(btnFlightTeamGroupID.Text).Tables[0];

            //焦点定位最后一条，增加一条后刷新定位最后一条（普通刷新也定位最后一条）
            //if (flightGridView.RowCount > 0)
            //    flightGridView.FocusedRowHandle = flightGridView.RowCount - 1;
        }
        private void flightGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;
            GridView gv = sender as GridView;
            string tourGroupId = gv.GetRowCellValue(e.FocusedRowHandle, "TourgroupID").ToString();
            //审核状态后的不能新增和删除内容
            TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(tourGroupId);
            if (state == TeamStateEnum.成行 || state == TeamStateEnum.分配)
            {
                //btnAddFlightOrder.Enabled = true;
                btnDeleteFlightOrder.Enabled = true;
                FlightDataModifyPanel.Enabled = true;
            }
            else
            {
                //btnAddFlightOrder.Enabled = false;
                btnDeleteFlightOrder.Enabled = false;
                FlightDataModifyPanel.Enabled = false;
            }

            DisplayScheduleData(gv);
        }

        #region 初始化绑定处理

        private void InitializeFlightGUIData()
        {
            if (_dtFlightOrderData != null && _dtFlightOrderData.Rows.Count > 0)
            {
                //清除已有绑定
                tbFlightSeat.DataBindings.Clear();

                tbFlightCode.DataBindings.Clear();
                tbFlightBeginPosition.DataBindings.Clear();
                tbFlightBeginPositionDate.DataBindings.Clear();
                tbFlightBeginPositionTime.DataBindings.Clear();
                tbFlightEndPosition.DataBindings.Clear();
                tbFlightEndPositionDate.DataBindings.Clear();
                tbFlightEndPositionTime.DataBindings.Clear();

                tbFlightAdultNum.DataBindings.Clear();
                tbFlightChildNum.DataBindings.Clear();
                tbFlightBabyNum.DataBindings.Clear();
                tbFlighAccompanyNum.DataBindings.Clear();

                tbFlightAdultUnitPrice.DataBindings.Clear();
                tbFlightChildUnitPrice.DataBindings.Clear();
                tbFlightBabyUnitPrice.DataBindings.Clear();
                tbFlightAccompanyUnitPrice.DataBindings.Clear();
                tbFlightHandlingCharge.DataBindings.Clear();
                tbFlightTotalPrice.DataBindings.Clear();

                tbFlightProviders.DataBindings.Clear();
                tbFlightRemark.DataBindings.Clear();

                //与UI绑定
                tbFlightSeat.DataBindings.Add("EditValue", _dtFlightOrderData, "Seat");

                tbFlightCode.DataBindings.Add("EditValue", _dtFlightOrderData, "FlightCode");
                tbFlightBeginPosition.DataBindings.Add("EditValue", _dtFlightOrderData, "BeginPosition");
                tbFlightBeginPositionDate.DataBindings.Add("EditValue", _dtFlightOrderData, "StartDate");
                tbFlightBeginPositionTime.DataBindings.Add("EditValue", _dtFlightOrderData, "StartTime");
                tbFlightEndPosition.DataBindings.Add("EditValue", _dtFlightOrderData, "EndPosition");
                tbFlightEndPositionDate.DataBindings.Add("EditValue", _dtFlightOrderData, "EndDate");
                tbFlightEndPositionTime.DataBindings.Add("EditValue", _dtFlightOrderData, "EndTime");

                tbFlightAdultNum.DataBindings.Add("EditValue", _dtFlightOrderData, "AdultNum");
                tbFlightChildNum.DataBindings.Add("EditValue", _dtFlightOrderData, "ChildNum");
                tbFlightBabyNum.DataBindings.Add("EditValue", _dtFlightOrderData, "BabyNum");
                tbFlighAccompanyNum.DataBindings.Add("EditValue", _dtFlightOrderData, "AccompanyNum");

                tbFlightAdultUnitPrice.DataBindings.Add("EditValue", _dtFlightOrderData, "AdultUnitPrice");
                tbFlightChildUnitPrice.DataBindings.Add("EditValue", _dtFlightOrderData, "ChildUnitPrice");
                tbFlightBabyUnitPrice.DataBindings.Add("EditValue", _dtFlightOrderData, "BabyUnitPrice");
                tbFlightAccompanyUnitPrice.DataBindings.Add("EditValue", _dtFlightOrderData, "AccompanyUnitPrice");
                tbFlightHandlingCharge.DataBindings.Add("EditValue", _dtFlightOrderData, "HandlingCharge");
                tbFlightTotalPrice.DataBindings.Add("EditValue", _dtFlightOrderData, "Budget");

                tbFlightProviders.DataBindings.Add("EditValue", _dtFlightOrderData, "ProviderName");
                tbFlightProviders.DataBindings.Add("Tag", _dtFlightOrderData, "ProviderID");
                tbFlightRemark.DataBindings.Add("EditValue", _dtFlightOrderData, "Remark");
            }
        } 
        #endregion

        #region 飞机预订信息修改

        private void btnFlightCode_Click(object sender, EventArgs e)
        {
            FlightOrderForm flightOrderForm = new FlightOrderForm()
            {
                _StartCity = tbFlightBeginPosition.EditValue.ToString(),
                _EndCity = tbFlightEndPosition.EditValue.ToString(),
            };
            if (flightOrderForm.ShowDialog(this) == DialogResult.OK)//设置各项返回值
            {
                tbFlightCode.EditValue = flightOrderForm._FlightCode;
                tbFlightBeginPosition.EditValue = flightOrderForm._StartCity;
                tbFlightEndPosition.EditValue = flightOrderForm._EndCity;
                tbFlightBeginPositionTime.EditValue = flightOrderForm._StartTime;
                tbFlightEndPositionTime.EditValue = flightOrderForm._EndTime;
            }
        }

        private void btnFlightSave_Click(object sender, EventArgs e)
        {
            if (_dtFlightOrderData == null || _dtFlightOrderData.Rows.Count == 0) return;

            DataRowView drv = (BindingContext[_dtFlightOrderData].Current as DataRowView);

            FlightOrderEntity flightOrderEntity = new FlightOrderEntity()
            {
                //变化内容提交
                AccompanyNum = int.Parse(tbFlighAccompanyNum.Text),
                AdultNum = int.Parse(tbFlightAdultNum.Text),
                ChildNum = int.Parse(tbFlightChildNum.Text),
                BabyNum = int.Parse(tbFlightBabyNum.Text),

                AdultUnitPrice = decimal.Parse(tbFlightAdultUnitPrice.EditValue.ToString()),
                ChildUnitPrice = decimal.Parse(tbFlightChildUnitPrice.EditValue.ToString()),
                BabyUnitPrice = decimal.Parse(tbFlightBabyUnitPrice.EditValue.ToString()),
                AccompanyUnitPrice = decimal.Parse(tbFlightAccompanyUnitPrice.EditValue.ToString()),
                HandlingCharge = decimal.Parse(tbFlightHandlingCharge.EditValue.ToString()),

                FlightCode = tbFlightCode.Text,
                StartDate = tbFlightBeginPositionDate.DateTime.ToString("yyyy-MM-dd"),
                EndDate = tbFlightEndPositionDate.DateTime.ToString("yyyy-MM-dd"),
                StartTime = DateTime.Parse(tbFlightBeginPositionTime.Text).ToString("HH:mm:ss"),
                EndTime = DateTime.Parse(tbFlightEndPositionTime.Text).ToString("HH:mm:ss"),
                BeginPosition = tbFlightBeginPosition.Text,
                EndPosition = tbFlightEndPosition.Text,
                Remark = tbFlightRemark.Text,

                ProviderID = tbTrainProviders.Tag == null ? -1 : int.Parse(tbTrainProviders.Tag.ToString()),
                ProviderName = tbTrainProviders.Text,

                Seat= tbFlightSeat.Text,

                FlightOrderID = int.Parse(drv["FlightOrderID"].ToString())  /*更新条件字段*/

            };
            //获取id并更新数据
            //string trainOrderId = (BindingContext[_dtTrainOrderData].Current as DataRowView).Row["TrainOrderID"].ToString();
            //TrainOrderCtrl.UpdateTrainOrderData(trainOrderId, trainOrderEntity);

            ExpenseEntity expense = new ExpenseEntity()
            {
                ExpenseID = int.Parse(drv["ExpenseID"].ToString()), /*重点字段*/
                //TourgroupID = drv["TourgroupID"].ToString(),
                //TourgroupName = drv["TourgroupName"].ToString(),
                ProviderID = tbFlightProviders.Tag == null ? -1 : int.Parse(tbFlightProviders.Tag.ToString()),
                ProviderName = tbFlightProviders.Text,
                Budget = decimal.Parse(tbFlightTotalPrice.EditValue.ToString()),
                ServiceName = tbFlightBeginPosition.Text+"-"+tbFlightEndPosition.Text+" 飞机票"
                //Status = drv["Status"].ToString(),
                //Remark = drv["Remark"].ToString(),
                //TypeBelong = ProviderTypeEnum.飞机票.ToString(),
            };
            FlightOrderCtrl.UpdateFlightOrderData(expense, flightOrderEntity);

            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(drv["TourgroupID"].ToString());

            MessageBox.Show("保存成功！", "保存数据", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //刷新界面，因希望保存后，列表焦点行不变，于是不刷新界面。缺点是不能实时刷新，要换一行才发现变化。
            //btnRefresh.PerformClick();
        }

        private void btnFlightCalculationPrice_Click(object sender, EventArgs e)
        {
            decimal totalPrice = int.Parse(tbFlightAdultNum.Text) * decimal.Parse(tbFlightAdultUnitPrice.EditValue.ToString()) +
                                int.Parse(tbFlightChildNum.Text) * decimal.Parse(tbFlightChildUnitPrice.EditValue.ToString()) +
                                int.Parse(tbFlightBabyNum.Text) * decimal.Parse(tbFlightBabyUnitPrice.EditValue.ToString()) +
                                int.Parse(tbFlighAccompanyNum.Text) * decimal.Parse(tbFlightAccompanyUnitPrice.EditValue.ToString()) +
                                decimal.Parse(tbFlightHandlingCharge.EditValue.ToString());
            tbFlightTotalPrice.EditValue = totalPrice;
        }

        #endregion

        #region 打印、预览、提交审核事件处理
        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFlightExpenseSubmit_Click(object sender, EventArgs e)
        {
            if (_dtFlightOrderData == null || _dtFlightOrderData.Rows.Count <= 0) return;

            if (MessageBox.Show("您确认提交选中内容进行审核吗？", "打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //flightGridView.ClearSelection();
                int[] rowIds = MutilRow(flightGridView);
                string expenseId = "", status = "";

                foreach (int id in rowIds)
                {
                    status = flightGridView.GetRowCellValue(id, "Status").ToString();
                    if (status == ExpenseStatusEnum.计划.ToString())
                    {
                        expenseId = flightGridView.GetRowCellValue(id, "ExpenseID").ToString();
                        ExpensesCtrl.UpdateExpenseStatusData(expenseId, ExpenseStatusEnum.待审核);

                        flightGridView.SetRowCellValue(id, "Status", ExpenseStatusEnum.待审核);
                    }
                }

              MessageBox.Show("提交完毕！", "提交审核", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 打印预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFlightPreview_Click(object sender, EventArgs e)
        {
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(flightGridView, out rowIds))
                return;

            //获取供应商名称列表及选择的数据行数据
            string providerNames = "";
            BatchFlightDataSet ds = new BatchFlightDataSet();

            for (int i = 0; i < rowIds.Length; i++)
            {
                if (flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                {
                    DataRow tmpDr = flightGridView.GetDataRow(rowIds[i]);

                    ds.Tables["Flight"].ImportRow(tmpDr);
                    ds.Tables["Flight"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                    ds.Tables["Flight"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                    ds.Tables["Flight"].Rows[i]["StartTime"] = DateTime.Parse(tmpDr["StartTime"].ToString()).ToString("HH:mm");
                }
                if (flightGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(flightGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                    providerNames = string.Format("{0}　{1}", providerNames, flightGridView.GetRowCellValue(rowIds[i], "ProviderName"));
            }
            BatchFlightOrderReport rpt = new BatchFlightOrderReport(providerNames);
            rpt.DataSource = ds;
            //new PrintPreviewForm(rpt, "").ShowDialog();
            rpt.ShowPreviewDialog();
        }
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFlightPrint_Click(object sender, EventArgs e)
        {
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(flightGridView, out rowIds))
                return;

            if (MessageBox.Show("您确认打印选中的机票预订信息吗？", "打印", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //获取供应商名称列表及选择的数据行数据
                string providerNames = "";
                BatchFlightDataSet ds = new BatchFlightDataSet();

                for (int i = 0; i < rowIds.Length; i++)
                {
                    if (flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                    {
                        DataRow tmpDr = flightGridView.GetDataRow(rowIds[i]);

                        ds.Tables["Flight"].ImportRow(tmpDr);
                        ds.Tables["Flight"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                        ds.Tables["Flight"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                        ds.Tables["Flight"].Rows[i]["StartTime"] = DateTime.Parse(tmpDr["StartTime"].ToString()).ToString("HH:mm");
                    }
                    if (flightGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(flightGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                        providerNames = string.Format("{0}　{1}", providerNames, flightGridView.GetRowCellValue(rowIds[i], "ProviderName"));
                }
                BatchFlightOrderReport rpt = new BatchFlightOrderReport(providerNames);
                rpt.DataSource = ds;
                if (rpt.PrintDialog() == DialogResult.OK)//打印完毕之后将订单状态变为‘已定’
                {
                    string flightOrderId = "";
                    foreach (int id in rowIds)
                    {
                        if (flightGridView.GetRowCellValue(id, "Status").ToString() != OrderStateEnum.取消.ToString())
                        {
                            flightOrderId = flightGridView.GetRowCellValue(id, "FlightOrderID").ToString();
                            FlightOrderCtrl.UpdateFlightOrderStateData(flightOrderId, OrderStateEnum.已订);
                            flightGridView.SetRowCellValue(id, "OrderState", OrderStateEnum.已订);
                        }
                    }
                    MessageBox.Show("打印完毕！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// 发送EMail
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFlightEmail_Click(object sender, EventArgs e)
        {
            if (_dtFlightOrderData == null || _dtFlightOrderData.Rows.Count <= 0) return;

            #region 生成报表
            int[] rowIds;
            //校验选择内容数据
            if (!ValidateData(flightGridView, out rowIds))
                return;

            //获取供应商名称列表及选择的数据行数据
            string providerNames = "";
            BatchFlightDataSet ds = new BatchFlightDataSet();

            for (int i = 0; i < rowIds.Length; i++)
            {
                if (flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != OrderStateEnum.取消.ToString())
                {
                    DataRow tmpDr = flightGridView.GetDataRow(rowIds[i]);

                    ds.Tables["Flight"].ImportRow(tmpDr);
                    ds.Tables["Flight"].Rows[i]["StartYear"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("yyyy年");
                    ds.Tables["Flight"].Rows[i]["StartDate"] = DateTime.Parse(tmpDr["StartDate"].ToString()).ToString("MM月dd日");
                    ds.Tables["Flight"].Rows[i]["StartTime"] = DateTime.Parse(tmpDr["StartTime"].ToString()).ToString("HH:mm");
                }
                if (flightGridView.GetRowCellValue(rowIds[i], "ProviderName") != null && !providerNames.Contains(flightGridView.GetRowCellValue(rowIds[i], "ProviderName").ToString()) && flightGridView.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.取消.ToString())
                    providerNames = string.Format("{0}　{1}", providerNames, flightGridView.GetRowCellValue(rowIds[i], "ProviderName"));
            }
            BatchFlightOrderReport rpt = new BatchFlightOrderReport(providerNames);
            rpt.DataSource = ds;

            #endregion

            #region 发送EMail

            //ProviderEntity entity;
            //StringBuilder info = new StringBuilder();
            List<string> receiveMail = new List<string>();
            //StringBuilder recipients = new StringBuilder();

            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "机票预订单.pdf");
            rpt.ExportToPdf(file);
            if (File.Exists(file))
            {
                string ReplyAddress = SysParameterCtrl.GetValueForKey("TicketMailAddress");
                //string ServerMailAddress = SysParameterCtrl.GetValueForKey("TicketMailServer");
                //string ServerMailPassword = SysParameterCtrl.GetValueForKey("TicketMailPassword");
                //string ServerMailSmtp = SysParameterCtrl.GetValueForKey("TicketMailSmtp");
                List<string> files = new List<string>();
                files.Add(file);

                string providerID = flightGridView.GetRowCellValue(rowIds[0], "ProviderID").ToString();
                if (string.IsNullOrEmpty(providerID) || providerID=="-1")
                {
                    MessageBox.Show("尚未确定供应商", "信息提示");
                    return;
                }
                ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);
                string emailAddress = provider.email.ToString();
                string recipients = flightGridView.GetRowCellValue(rowIds[0], "ProviderName").ToString();

                if (string.IsNullOrEmpty(emailAddress) || (emailAddress.IndexOf("@") < 1) || (emailAddress.Substring(emailAddress.IndexOf("@")).IndexOf(".") < 2))
                {
                    MessageBox.Show("当前接收人地址格式不正确", "信息提示");
                    return;
                }

                for (int i = 1; i < rowIds.Length; i++)
                {
                    if (providerID != flightGridView.GetRowCellValue(rowIds[i], "ProviderID").ToString())
                    {
                        MessageBox.Show("请选择同一收件人", "信息提示");
                        return;
                    }
                }
                receiveMail.Add(emailAddress);

                if (EMailHelper.SendMail(receiveMail, "机票预订", "请收到此通知后回复确认。\r\n\r\n北京龙润国际旅行社有限公司", files, ReplyAddress, recipients, "", "", LogTypeEnum.计调类))
                {
                    MessageBox.Show("邮件发送成功！", "信息提示");
                    string FlightOrderID = "";
                    foreach (int id in rowIds)
                    {
                        if (flightGridView.GetRowCellValue(id, "Status").ToString() != OrderStateEnum.取消.ToString())
                        {
                            FlightOrderID = flightGridView.GetRowCellValue(id, "FlightOrderID").ToString();
                            FlightOrderCtrl.UpdateFlightOrderStateData(FlightOrderID, OrderStateEnum.已订);
                            trainGridView.SetRowCellValue(id, "OrderState", OrderStateEnum.已订);
                        }
                    }

                }
                else
                    MessageBox.Show("邮件发送失败，详情请查看日志", "信息提示");
                File.Delete(file);
            }
            else
            {
                MessageBox.Show("发送失败,生成报表文件失败！", "信息提示");
            }
        #endregion
  
            
        } 

        #endregion

        #region 飞机预订的新增、删处理（在“火车飞机”计调处可新增项的新需求）

        private void btnAddFlightOrder_Click(object sender, EventArgs e)
        {
            if (btnFlightTeamGroupID.Text == "")
            {
                MessageBox.Show("您还没有选择‘计划号’！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ////先刷新行程，使之与当前选择团号一致
            //DisplayScheduleData(flightGridView);

            ////判断当前是否有选择的团一致行程计划
            //if (ScheduleGridView.FocusedRowHandle < 0)
            //{
            //    MessageBox.Show(string.Format("团‘{0}’没有安排行程计划，无法添加预订！", btnFlightTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            string tourGroupName = TeamGroupCtrl.GetTeamGroupNameById(btnFlightTeamGroupID.Text);

            TeamStateEnum state = TeamGroupCtrl.GetTourGroupState(btnFlightTeamGroupID.Text);
            if (state != TeamStateEnum.成行 && state != TeamStateEnum.分配)
            {
                MessageBox.Show(string.Format("团‘{0}’未成行或已审核，无法添加预订！", btnFlightTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int scheduleId = TeamGroupCtrl.GetFirstTourgroupScheduleID(btnFlightTeamGroupID.Text);

            //判断当前是否有选择的团一致行程计划
            if (scheduleId < 0)
            {
                MessageBox.Show(string.Format("团‘{0}’没有安排行程计划，无法添加预订！", btnFlightTeamGroupID.Text), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //创建飞机预定信息内容
            FlightOrderEntity flightOrder = new FlightOrderEntity();
            flightOrder.OrderState = OrderStateEnum.未订.ToString();/*重点内容，初始化订单状态为‘未定’*/
            flightOrder.FlightCode = "";
            flightOrder.AccompanyNum = 0;
            flightOrder.AdultNum = 0;
            flightOrder.BabyNum = 0;
            flightOrder.ChildNum = 0;
            flightOrder.BeginPosition = "";
            flightOrder.EndPosition = "";
            flightOrder.StartDate = DateTime.Now.ToString("yyyy-MM-dd");
            flightOrder.EndDate = DateTime.Now.ToString("yyyy-MM-dd");

            flightOrder.StartTime = "00:00:00";
            flightOrder.EndTime = "00:00:00";

            flightOrder.Remark = "";
            flightOrder.AccompanyUnitPrice = 0;
            flightOrder.AdultUnitPrice = 0;
            flightOrder.BabyUnitPrice = 0;
            flightOrder.ChildUnitPrice = 0;
            flightOrder.HandlingCharge = 0;
            //FlightID=0;
            flightOrder.TourGroupScheduleID = scheduleId;
            flightOrder.TourgroupID = btnFlightTeamGroupID.Text;
            flightOrder.TourgroupName = tourGroupName;
            flightOrder.ProviderID = -1;
            flightOrder.ProviderName = "";

            flightOrder.Seat = "";

            //创建费用
            ExpenseEntity expense = new ExpenseEntity()
            {
                //ExpenseID = _ExpenseID,
                TourgroupID = btnFlightTeamGroupID.Text,
                TourgroupName = tourGroupName,
                ProviderID = -1,
                ProviderName = "",
                ServiceName = "",
                Budget = 0,
                PayTotal = 0,
                ApplyPayTotal = 0,
                AdjustAmount = 0,
                Status = ExpenseStatusEnum.计划.ToString(),
                TypeBelong = ProviderTypeEnum.飞机票.ToString(),
                ApplyPay = 0,
                PayStatus = PayApplyStatusEnum.未付.ToString(),
                CreateByUserName = Thread.CurrentPrincipal.Identity.Name,
                TourGroupScheduleID = scheduleId,
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                ExpenseTypeID = 4,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(4)//同上
            };
            FlightOrderCtrl.CreateFlightOrderAndExpenseData(expense, flightOrder);
            btnFlightRefresh.PerformClick();//刷新显示
        }

        private void btnDeleteFlightOrder_Click(object sender, EventArgs e)
        {
            if (flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString()
                || flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "OrderState").ToString() != OrderStateEnum.未订.ToString())
            {
                MessageBox.Show("该预订已生效，不能删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //删除已有飞机预订信息
            if (MessageBox.Show("确定取消选中的预订信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int flightOrderId = int.Parse(flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "FlightOrderID").ToString());
                FlightOrderCtrl.DeleteFlightOrder(flightOrderId);

                //刷新
                flightGridView.DeleteRow(flightGridView.FocusedRowHandle);

            }
        }

        private void btnCancelFlightOrder_Click(object sender, EventArgs e)
        {

            if (flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "Status").ToString() != ExpenseStatusEnum.计划.ToString()
                || flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "PayStatus").ToString() != PayApplyStatusEnum.未付.ToString())
            {
                MessageBox.Show("该预订已支付或提交审核，不能取消！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (MessageBox.Show("确定取消选中的预订信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string expenseId = flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "ExpenseID").ToString();
                string flightOrderId = flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "FlightOrderID").ToString();
                FlightOrderCtrl.UpdateFlightOrderStateData(flightOrderId, OrderStateEnum.取消);
                ExpensesCtrl.UpdateExpenseStatusData(expenseId, ExpenseStatusEnum.取消);
 
                //刷新
                flightGridView.SetRowCellValue(flightGridView.FocusedRowHandle, "Status", ExpenseStatusEnum.取消);
                flightGridView.SetRowCellValue(flightGridView.FocusedRowHandle, "OrderState", ExpenseStatusEnum.取消);
            }
        }


        #endregion

        #endregion

        #region 打印火车或飞机的结算单

        private void btnTrainAndFlightPrintClearingBill_Click(object sender, EventArgs e)
        {
            GridView gv;
            if (sender.Equals(btnTrainPrintClearingBill) || sender.Equals(btnTrainPreviewClearingBill))
                gv = trainGridView;
            else
                gv = flightGridView;

            decimal totalpayment;
            string providerID;
            int[] rowIds;

            //校验选择内容数据
            if (!ValidateData(gv, out totalpayment, out providerID, out rowIds))
                return;

            if (sender.Equals(btnTrainPrintClearingBill) || sender.Equals(btnFlightPrintClearingBill))
            {

                if (DialogResult.Yes == MessageBox.Show("请注意，本次打印的同时将会一并发送申请单到财务，过程不可逆，是否确认？", "打印确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    //任选一项提取供应商信息
                    ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);
                    if (provider != null)
                    {
                        #region 生成付款申请单和付款申请单详情数据
                        string currentUser = UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name);//当前登录者

                        //准备付款申请单数据
                        PayApplyEntity payApplyEntity = new PayApplyEntity()
                        {
                            //PayApplyID = ,
                            ProviderName = provider.ProviderName,
                            ProviderID = provider.ProviderID,
                            Contact = "",//tbContact.Text,
                            Telephone = provider.Telephone,
                            Fax = provider.fax,
                            TotalpaymentG = MoneyHelper.ChMoney(totalpayment),
                            TotalpaymentL = totalpayment,
                            Applicants = currentUser,
                            Audit = "",
                            PlanPayTime = provider.IsSigned == 1 ? "月结" : "",//是月结供应商则‘月结’，否则提供拟汇款时间
                            ApplyPayTime = DateTime.Today.ToString("yyyy-MM-dd"),//申请时间
                            PayTime = "",//财务付款时间
                            PayStatus = PayStatusEnum.未付.ToString(),
                            Remark = currentUser + " 申请 " + provider.ProviderName + " 票款"
                        };

                        //准备付款详情数据
                        string[] providerIds = new string[rowIds.Length];
                        PayDetailEntity[] payDetailEntity = new PayDetailEntity[rowIds.Length];

                        for (int i = 0; i < rowIds.Length; i++)//为每一条数据创建一条付款详情信息——供历史查询
                        {
                            payDetailEntity[i] = new PayDetailEntity();
                            //entity[i].PayApplyID = payApplyId;
                            payDetailEntity[i].ExpenseID = int.Parse(gv.GetRowCellValue(rowIds[i], "ExpenseID").ToString());
                            payDetailEntity[i].ApplyPay = decimal.Parse(gv.GetRowCellValue(rowIds[i], "Budget").ToString());//将‘预算额’作为申请额，一次性申请
                            payDetailEntity[i].PayStatus = PayDetailStatusEnum.未付.ToString();
                        }
                        //写入付款单及付款详情数据
                        string payApplyId = PayApplyCtrl.CreatePayApplyAndPayDetailData(payApplyEntity, payDetailEntity);

                        #endregion

                        #region 写入费用表中‘已申请总额’

                        Dictionary<int, decimal> data = new Dictionary<int, decimal>();
                        Dictionary<int, string> tourGroupIds = new Dictionary<int, string>();

                        for (int i = 0; i < rowIds.Length; i++)
                        {
                            //DataRowView drv = BindingContext[_dtPayApply].Current as DataRowView;
                            decimal applyPay = gv.GetRowCellValue(rowIds[i], "Budget").ToString() == "" ? 0 : decimal.Parse(gv.GetRowCellValue(rowIds[i], "Budget").ToString());//本次申请额
                            decimal applyPayTotal = gv.GetRowCellValue(rowIds[i], "ApplyPayTotal").ToString() == "" ? 0 : decimal.Parse(gv.GetRowCellValue(rowIds[i], "ApplyPayTotal").ToString());//已申请总额
                            int expenseId = int.Parse(gv.GetRowCellValue(rowIds[i], "ExpenseID").ToString());
                            string tourGroupId = gv.GetRowCellValue(rowIds[i], "TourgroupID").ToString();

                            gv.SetRowCellValue(rowIds[i], "ApplyPayTotal", applyPayTotal + applyPay);//更新界面‘已申请总额’单元格
                            data.Add(expenseId, applyPayTotal + applyPay);
  
                            tourGroupIds.Add(expenseId, tourGroupId);

                            ExpensesCtrl.UpdateExpenseApplyPayTotal(expenseId);
                        }

                        //更新团实际成本
                        TeamGroupCtrl.UpdateTourGroupRealCostbyGourpIDs(tourGroupIds);

                        #endregion

                        #region 提交审核
                        string status = "";

                        foreach (int id in rowIds)
                        {
                            status = gv.GetRowCellValue(id, "Status").ToString();
                            if (status == ExpenseStatusEnum.计划.ToString())
                            {
                                ExpensesCtrl.UpdateExpenseStatusData(gv.GetRowCellValue(id, "ExpenseID").ToString(), ExpenseStatusEnum.待审核);

                                gv.SetRowCellValue(id, "Status", ExpenseStatusEnum.待审核);
                            }
                        }
                        #endregion

                        #region 打印结算单（报表）

                        //BatchTrainFlightDataSet ds = new BatchTrainFlightDataSet();


                        if (sender.Equals(btnTrainPrintClearingBill))//火车
                        {
                            BatchTrainDataSet ds = new BatchTrainDataSet();
                            for (int i = 0; i < rowIds.Length; i++)
                                ds.Tables["Train"].ImportRow(gv.GetDataRow(rowIds[i]));

                            ds.Tables["fin_PayApply"].Rows.Add();
                            ds.Tables["fin_PayApply"].Rows[0]["PayApplyID"] = payApplyId;

                            TrainClearingBillReport rpt = new TrainClearingBillReport(provider.ProviderName);
                            rpt.DataSource = ds;
                            rpt.ShowPreviewDialog();
                        }
                        else //飞机
                        {
                            BatchFlightDataSet ds = new BatchFlightDataSet();
                            for (int i = 0; i < rowIds.Length; i++)
                                ds.Tables["Flight"].ImportRow(gv.GetDataRow(rowIds[i]));

                            ds.Tables["fin_PayApply"].Rows.Add();
                            ds.Tables["fin_PayApply"].Rows[0]["PayApplyID"] = payApplyId;

                            FlightClearingBillReport rpt = new FlightClearingBillReport(provider.ProviderName);
                            rpt.DataSource = ds;
                            rpt.ShowPreviewDialog();
                        }

                        #endregion

                    }
                }
            }
            else
            {
                //任选一项提取供应商信息
                ProviderEntity provider = BaseInfoCtrl.GetProviderDataByID(providerID);

                #region 预览结算单（报表）

                //BatchTrainFlightDataSet ds = new BatchTrainFlightDataSet();

                if (sender.Equals(btnTrainPreviewClearingBill))//火车
                {
                    BatchTrainDataSet ds = new BatchTrainDataSet();
                    for (int i = 0; i < rowIds.Length; i++)
                        ds.Tables["Train"].ImportRow(gv.GetDataRow(rowIds[i]));

                    TrainClearingBillReport rpt = new TrainClearingBillReport(provider.ProviderName);
                    rpt.DataSource = ds;
                    rpt.ShowPreviewDialog();
                }
                else //飞机
                {
                    BatchFlightDataSet ds = new BatchFlightDataSet();
                    for (int i = 0; i < rowIds.Length; i++)
                        ds.Tables["Flight"].ImportRow(gv.GetDataRow(rowIds[i]));

                    FlightClearingBillReport rpt = new FlightClearingBillReport(provider.ProviderName);
                    rpt.DataSource = ds;
                    rpt.ShowPreviewDialog();
                }

                #endregion
            }
        }
        /// <summary>
        /// 校验选择数据是否合法
        /// </summary>
        /// <param name="totalpayment">校验通过，返回本次申请额总和</param>
        /// <param name="providerID">校验通过，返回供应商ID</param>
        /// <param name="rowIds">返回所有选中的行号</param>
        /// <returns>校验是否通过</returns>
        private bool ValidateData(GridView gv, out decimal totalpayment, out string providerID, out int[] rowIds)
        {
            msg.Clear();

            //判断是否是同一供应商，以及本次申请费用和
            totalpayment = 0;
            providerID = "";

            //gv.ClearSelection();
            rowIds = MutilRow(gv);

            if (rowIds.Length >= 1)
            {
                providerID = gv.GetRowCellValue(rowIds[0], "ProviderID").ToString();
                string providerName = gv.GetRowCellValue(rowIds[0], "ProviderName").ToString();
                if (providerName.Trim() == "")
                {
                     msg.AppendText("尚未指定供应商，请指定供应商\r\n");
                     messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                     return false;
                }

                totalpayment = decimal.Parse(gv.GetRowCellValue(rowIds[0], "Budget").ToString());
                for (int i = 0; i < rowIds.Length; i++)
                {
                    if (providerID != gv.GetRowCellValue(rowIds[i], "ProviderID").ToString())
                    {
                        msg.AppendText("选中项的各个'供应商'不完全相同，请选择相同供应商项\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }
                    if (decimal.Parse(gv.GetRowCellValue(rowIds[i], "Budget").ToString()) == 0)
                    {
                        msg.AppendText("选择项中有'预算额'为空项,不能打印\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }
                    if (gv.GetRowCellValue(rowIds[i], "Status").ToString() != ExpenseStatusEnum.计划.ToString())
                    {
                        msg.AppendText("选择项中有的费用已提交申请或已取消,不能打印\r\n");
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }
                    string payApplyStatus = gv.GetRowCellValue(rowIds[i], "PayStatus").ToString();
                    if (payApplyStatus == PayApplyStatusEnum.已付.ToString() || payApplyStatus == PayApplyStatusEnum.付清.ToString())
                    {
                        msg.AppendText(string.Format("选择项中存在‘支付状态’为‘{0}’,不能打印\r\n", payApplyStatus));
                        messageDockPanel.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
                        return false;
                    }
                    if (i != 0)    //非第一行
                        totalpayment += decimal.Parse(gv.GetRowCellValue(rowIds[i], "Budget").ToString());
                }
                return true;
            }
            msg.AppendText("没有选择任何内容，请在选择项上打‘√’\r\n");
            return false;
        }
        #endregion

        private void trainFlightTab_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            switch (e.Page.Name)
            {
                case "FlightPage":
                    btnFlightRefresh.PerformClick();
                    break;
                case "TrainPage":
                    btnTrainRefresh.PerformClick();
                    break;
                default://EtcPage
                    break;
            }
        }

        private bool ValidateData(GridView gv, out int[] rowIds)
        {
            string providerID = "";

            //判断是否是同一供应商
            //gv.ClearSelection();
            rowIds = MutilRow(gv);

            if (rowIds.Length >= 1)
            {
                providerID = gv.GetRowCellValue(rowIds[0], "TourgroupID").ToString();

                for (int i = 0; i < rowIds.Length; i++)
                    if (providerID != gv.GetRowCellValue(rowIds[i], "TourgroupID").ToString())
                    {
                        MessageBox.Show("选中项的'计划号'不完全相同，请选择相同计划号内容项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                return true;
            }
            MessageBox.Show("没有选择任何内容，请在选择项上打‘√’", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return false;
        }

        /// <summary>
        /// 客人列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGuestList_Click(object sender, EventArgs e)
        {
            string tourGroupId = "";
            if (sender.Equals(btnTrainGuestList))
                tourGroupId = trainGridView.GetRowCellValue(trainGridView.FocusedRowHandle, "TourgroupID").ToString();

            if (sender.Equals(btnFlightGuestList))
                tourGroupId = flightGridView.GetRowCellValue(flightGridView.FocusedRowHandle, "TourgroupID").ToString();
            GuestListForm guestListForm = new GuestListForm(tourGroupId);
            guestListForm.ShowDialog(this);
        }

        #region 打钩选择处理

        /// <summary>
        /// 添加‘选择’附加列
        /// </summary>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        private DataTable AddGridSelectedColumn(DataTable dtSource)
        {
            dtSource.Columns.Add("Selected", typeof(bool));
            return dtSource;
        }

        private void FlightSelectedCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            //int iFocuse = flightGridView.FocusedRowHandle;
            //flightGridView.ClearSelection();

            //if ((sender as CheckEdit).Checked)
            //    flightGridView.SelectRow(iFocuse);
            
            ////打钩后设定为选择
            //MutilRow(flightGridView);
        }
        private void TrainSelectedCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            //int iFocuse = trainGridView.FocusedRowHandle;
            //trainGridView.ClearSelection();

            //if ((sender as CheckEdit).Checked)
            //    trainGridView.SelectRow(iFocuse);

            ////打钩后设定为选择
            //MutilRow(trainGridView);
        }
        private int[] MutilRow(GridView gv)
        {
            List<int> rowIds = new List<int>();
            for (int i = 0; i < gv.RowCount; i++)
            {
                object objValue = gv.GetRowCellValue(i, "Selected");
                if (objValue != null)
                {
                    bool check = false;
                    bool.TryParse(objValue.ToString(), out check);
                    if (check)
                    {
                        rowIds.Add(i);
                    }
                }
            }
            return rowIds.ToArray();

            //object selected;
            //for (int i = 0; i < gv.RowCount; i++)
            //{
            //    selected = gv.GetRowCellValue(i, "Selected");

            //    if (string.IsNullOrEmpty(selected.ToString())) continue;

            //    if (Convert.ToBoolean(selected) == true)
            //    {
            //        gv.SelectRow(i);
            //    }
            //}
            //return gv.GetSelectedRows();
        }
        #endregion

        private void tbSelectedAll_CheckedChanged(object sender, EventArgs e)
        {
            if(sender.Equals(tbTrainAll))
                foreach (DataRow dr in _dtTrainOrderData.Rows)
                    dr["Selected"] = tbTrainAll.Checked;

            if (sender.Equals(tbFlightAll))
                foreach (DataRow dr in _dtFlightOrderData.Rows)
                    dr["Selected"] = tbFlightAll.Checked;
        }

        private void trainGridView_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle < 0) return;

            GridView gv = sender as GridView;

            object orderState = gv.GetRowCellValue(e.RowHandle, "OrderState");
            if (orderState.ToString() == OrderStateEnum.已订.ToString())
                e.Appearance.BackColor = Color.LightSteelBlue;

            object status = gv.GetRowCellValue(e.RowHandle, "Status");
            if (status.ToString() == ExpenseStatusEnum.待审核.ToString())
                e.Appearance.BackColor = Color.DarkKhaki;
            else if (status.ToString() == ExpenseStatusEnum.审核.ToString())
                e.Appearance.BackColor = Color.LightGreen;
            else if (status.ToString() == ExpenseStatusEnum.取消.ToString())
                e.Appearance.BackColor = Color.DarkOrchid;


            object payStatus = gv.GetRowCellValue(e.RowHandle, "PayStatus");
            if (payStatus.ToString() == PayApplyStatusEnum.已付.ToString())
                e.Appearance.BackColor = Color.Salmon;
            else if (payStatus.ToString() == PayApplyStatusEnum.付清.ToString())
                e.Appearance.BackColor = Color.Silver;
        }




    }
    /// <summary>
    /// 界面可用状态控制类
    /// </summary>
    class UiState
    {
        private bool isEnabled;

        public bool IsEnabled
        {
            get { return isEnabled; }
            set { isEnabled = value; }
        }
    }
}
